package com.study.controller;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.study.service.CacheService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Nonnull;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * @author zhuzi
 * 2024/2/20 16:56
 */
@Slf4j
@RestController
@RequestMapping("cache")
public class CacheController {
    @Resource
    CacheService cacheService;
    private static LoadingCache<String, LocalDateTime> transCache;

    @PostConstruct
    public void init() {
        // CacheBuilder的构造函数是私有的，只能通过其静态方法newBuilder()来获得CacheBuilder的实例
        transCache = CacheBuilder.newBuilder()
                // 设置并发级别为3，并发级别是指可以同时写缓存的线程数
                .concurrencyLevel(3)
                // 过期
                .expireAfterWrite(15, TimeUnit.SECONDS)
                // 初始容量
                .initialCapacity(100)
                // 最大容量，超过LRU
                .maximumSize(200).build(new CacheLoader<String, LocalDateTime>() {
                    @Override
                    public LocalDateTime load(@Nonnull String key) {
                        return cacheService.localTime(key);
                    }
                });
    }

    @GetMapping("{id}")
    public LocalDateTime local(@PathVariable("id") String id) {
        //如果缓存没有返回null
        LocalDateTime localDateTime = transCache.getIfPresent(id);

        //会直接抛出异常
        //localDateTime=transCache.getUnchecked(id);
        try {
            localDateTime = transCache.get(id);
        } catch (Exception e) {
            log.error("异常");
        }
        log.info("{}--{}", id, localDateTime);
        return localDateTime;
    }
}
